package cn.com.dashihui.web.controller;

import java.io.IOException;

import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authc.credential.PasswordService;

import com.jfinal.aop.Clear;
import com.jfinal.aop.Duang;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.upload.UploadFile;

import cn.com.dashihui.kit.DirKit;
import cn.com.dashihui.kit.ValidateKit;
import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.dao.Store;
import cn.com.dashihui.web.service.StoreService;

public class SystemController extends BaseController{
	private StoreService storeService = Duang.duang(new StoreService());
//    private static final int DEFAULT_CAPTCHA_LEN = 4;
	
    public void index(){
		this.render("index.jsp");
    }
    
    @Clear
    public void login(){
        this.render("login.jsp");
    }
    
//    @ActionKey("/img")
//    public void img(){
//        CaptchaRender img = new CaptchaRender(DEFAULT_CAPTCHA_LEN);
//        this.setSessionAttr(CaptchaRender.DEFAULT_CAPTCHA_MD5_CODE_KEY, img.getMd5RandomCode());
//        this.render(img);
//    }
    
    /**
     * 登录操作
     * @return 1：用户名为空，2：密码为空，3：用户名或密码错误（用户名不存在），4：用户名或密码错误（密码错误）
     */
    @Clear
    public void doLogin(){
    	String username = getPara("username");
    	String password = getPara("password");
    	if(StrKit.isBlank(username)){
    		//用户名为空
    		this.renderResult(1);
    	}else if(StrKit.isBlank(password)){
    		//密码为空
    		this.renderResult(2);
    	}else{
    		Store user = storeService.findByUsername(username);
    		if (null == user) {
    			//用户名或者密码错误
    			this.renderResult(3);
    		}else{
	    		//加密密码匹配方法
	    		PasswordService svc = new DefaultPasswordService();
	    		if(svc.passwordsMatch(password, user.getStr("password"))){
	    			//登录成功，放入session
	    			setSessionAttr(PropKit.get("constants.sessionUserKey"), user);
	    			this.renderSuccess();
	    		}else{
	    			//用户名或者密码错误
	    			this.renderResult(4);
	    		}
    		}
    	}
    }
    
	public void toEditMinePwd(){
		render("editMinePwd.jsp");
	}
	
	/**
	 * 更新当前登录用户的密码
	 * @return -1：异常，0：成功，1：密码为空，2：密码过长
	 */
	public void doEditMinePwd(){
		//原密码
		String passwordOld = getPara("passwordOld");
		//新设密码
		String passwordNew = getPara("passwordNew");
		if(StrKit.isBlank(passwordOld)){
			renderResult(1);
			return;
		}else if(StrKit.isBlank(passwordNew)){
			renderResult(2);
			return;
		}else if(passwordNew.length()>100){
			renderResult(3);
			return;
		}else{
			//更新
			try {
				if(storeService.editMinePwd(getCurrentUser(),passwordOld,passwordNew)){
					renderSuccess();
					return;
				}
			} catch (Exception e) {
				e.printStackTrace();
				//原密码输入错误
				renderResult(4);
				return;
			}
		}
		renderFailed();
	}
	
	public void toEditMineInfo(){
		setAttr("object", storeService.findById(getStoreid()));
		render("editMineInfo.jsp");
	}
	
	/**
	 * 更新当前登录用户的信息
	 * @return -1：异常，0：成功，1：便利店名称为空，2：便利店名称过长，6：详情地址为空，7：详细地址过长，8：图片为空，9：图片上传失败
	 */
	public void doEditMineInfo(){
		UploadFile thumb = getFile("thumb");
		//店铺名称
		String title = getPara("title");
		//店长
		String manager = getPara("manager");
		//电话
		String tel = getPara("tel");
		//邮箱
		String mail = getPara("mail");
		//营业开始时间
		String beginTime = getPara("beginTime");
		//营业结束时间
		String endTime = getPara("endTime");
		//配送说明
		String deliverydes = getPara("deliverydes");
		//省、市、县/区
		int province = getParaToInt("province",0),city = getParaToInt("city",0),area = getParaToInt("area",0);
		//详细地址
		String address = getPara("address");
		//旧图片
		String thumbOld = getPara("thumbOld");
		if(StrKit.isBlank(title)){
			renderResult(1);
			return;
		}else if(title.length()>50){
			renderResult(2);
			return;
		}else if(StrKit.isBlank(manager)){
			renderResult(3);
			return;
		}else if(manager.length()>20){
			renderResult(4);
			return;
		}else if(StrKit.notBlank(tel) && !ValidateKit.Tel(tel) && !ValidateKit.Mobile(tel)){
			renderResult(5);
			return;
		}else if(StrKit.notBlank(mail) && !ValidateKit.Email(mail)){
			renderResult(6);
			return;
		}else if(StrKit.notBlank(deliverydes) && deliverydes.length()>200){
			renderResult(7);
			return;
		}else if(province==0||city==0||area==0){
			renderResult(8);
			return;
		}else if(StrKit.isBlank(address)){
			renderResult(9);
			return;
		}else if(address.length()>100){
			renderResult(10);
			return;
		}else{
			//更新
			Store store = storeService.findById(getStoreid());
			store.set("title", title)
				.set("manager", manager)
				.set("province", province)
				.set("city", city)
				.set("area", area)
				.set("address", address);
			if(thumb!=null){
				//如果修改了图片，则上传新图片，删除旧图片
				String thumbFileName;
				String dir = DirKit.getDir(DirKit.STORE_LOGO);
				try {
					thumbFileName = uploadToFtp(dir,thumb);
					deleteFromFtp(thumbOld);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(6);
					return;
				}
				store.set("thumb", dir.concat(thumbFileName));
			}
			if(StrKit.notBlank(tel)){
				store.set("tel", tel);
			}
			if(StrKit.notBlank(mail)){
				store.set("mail", mail);
			}
			if(StrKit.notBlank(beginTime)){
				store.set("beginTime", beginTime);
			}
			if(StrKit.notBlank(endTime)){
				store.set("endTime", endTime);
			}
			if(StrKit.notBlank(deliverydes)){
				store.set("deliverydes", deliverydes);
			}
			if(storeService.editStore(store)){
				//刷新session中的店铺对象
				setSessionAttr(PropKit.get("constants.sessionUserKey"), store);
				renderSuccess(store);
				return;
			}
		}
		renderFailed();
	}

    public void logout() {
    	if(getCurrentUser()!=null){
    		removeSessionAttr(PropKit.get("constants.sessionUserKey"));
    	}
	    this.redirect("/login");
    }
    
    public void error401(){
    	render("401.jsp");
    }
    
    public void error403(){
    	render("403.jsp");
    }
    
    public void error404(){
    	render("404.jsp");
    }
    
    public void error500(){
    	render("500.jsp");
    }
}
